package cn.cyber.wxfire.controller;

import cn.cyber.wxfire.config.WXConfig;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Arrays;

/**
 * @author gjn
 * @since 2021/9/17 22:54
 */
@RestController
@CrossOrigin
@RequestMapping("wx")
public class WXController {
    @Resource
    private WXConfig config;

    /**
     * 验证接口配置信息
     * @param signature 微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
     * @param timestamp 时间戳
     * @param nonce     随机数
     * @param echostr   随机字符串
     * @return
     */
    @GetMapping("/check")
    public String check(@RequestParam("signature")String signature,
                        @RequestParam("timestamp")String timestamp,
                        @RequestParam("nonce")String nonce,
                        @RequestParam("echostr")String echostr){
        String token = config.getToken();
        String[] str = {token,timestamp,nonce};
        //排序
        Arrays.sort(str);
        //组成一个字符串
        String rawStr = str[0]+str[1]+str[2];

        //加密
        String encodeStr = DigestUtils.sha1Hex(rawStr);
        if(encodeStr.equalsIgnoreCase(signature)){
            System.out.println("接入成功");
            return echostr;
        }else{
            System.out.println("接入失败");
            return "接入失败";
        }
    }
}
